<template>
<el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>基本资料</span>
  </div>
  <el-form label-width="80px" :model="userInfoForm" :rules="userInfoRules" ref="userInfo">
    <el-form-item label="登录名称">
      <el-input disabled :placeholder="username"></el-input>
    </el-form-item>
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="userInfoForm.nickname"></el-input>
    </el-form-item>
    <el-form-item label="用户邮箱" prop="email">
      <el-input v-model="userInfoForm.email"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="changeUserInfo">提交修改</el-button>
      <el-button type="info" @click="resetFn">重置</el-button>
    </el-form-item>
  </el-form>
</el-card>
</template>
<script>
import { updateUserInfoAPI } from '@/api'
export default {
  name: 'userInfo',
  data () {
    return {
      username: this.$store.state.userInfo.username,
      userInfoForm: {
        id: '', // 用户id
        nickname: '', // 用户昵称
        email: ''// 用户邮箱
      },
      userInfoRules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '用户昵称为1-10位非空格字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    changeUserInfo () {
      this.$refs.userInfo.validate(async valid => {
        if (!valid) return false
        console.log(this.userInfoForm)
        this.userInfoForm.id = this.$store.state.userInfo.id
        const { data: res } = await updateUserInfoAPI(this.userInfoForm)
        console.log(res)
        if (res.code !== 0) return this.$message.error('修改用户信息失败！')
        this.$message.success('修改用户信息成功！')
        this.$store.dispatch('getUserInfo')// 重新获取用户信息
        this.$refs.userInfo.resetFields()
      })
    },
    resetFn () {
      // 清空表单
      this.$refs.userInfo.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
.el-button {
      padding: 10px 20px;
}
</style>
